package src.threadpool;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 演示暂停和恢复线程池
 */
public class PauseableThreadPool extends ThreadPoolExecutor {
    private volatile boolean isPaused = false;

    public PauseableThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, java.util.concurrent.TimeUnit unit,
                                java.util.concurrent.BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    public void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        while (isPaused) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    public void pause() {
        isPaused = true;
    }

    public void resume() {
        isPaused = false;
    }

    public static void main(String[] args) {
        PauseableThreadPool pool = new PauseableThreadPool(2, 4, 60, java.util.concurrent.TimeUnit.SECONDS,
                new java.util.concurrent.LinkedBlockingQueue<>());

        for (int i = 0; i < 10; i++) {
            pool.execute(new Task());
        }

        pool.pause();
        System.out.println("Thread pool paused");

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        pool.resume();
        System.out.println("Thread pool resumed");
    }
}
